<template>
  <div id="roles" v-loading="loading">
    <!-- 1.面包导航 -->
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>部门管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片主体 -->
    <el-card class="box-card">
      <div class="block">
        <!-- 2.搜索区域 -->
        <el-page-header style="margin-bottom: 2vh" @back="goBack" :content="this.$router.currentRoute.name.substring(this.$router.currentRoute.name.indexOf('/')+1)">
        </el-page-header>
        <!-- 2.搜索区域 -->
        <el-row>
          <el-col :span="16">
            <div class="grid-content bg-purple">
              <el-input placeholder="输入关键字进行过滤" v-model="filterText" clearable></el-input>
            </div>
          </el-col>
          <el-col :span="2">
            <div class="grid-content bg-purple-light">
              <el-button
                  type="primary"
                  icon="el-icon-plus"
                  style="margin-left:20px;"
                  @click="openParentAdd"
              >根部门</el-button>
            </div>
          </el-col>


        </el-row>

        <el-row>
          <h4 style="margin: 1vh 0 2vh;color: #1f2d3d">部门树</h4>
        </el-row>
        <el-table :data="data" row-key="deptId" border style="width: 100%" ref="tree">
          <el-table-column
              prop="deptName"
              header-align="left"
              min-width="70"
              label="部门名称"
          >
          </el-table-column>
          <el-table-column
              prop="remarks"
              header-align="center"
              align="center"
              label="描述"
          >
          </el-table-column>

          <el-table-column
              prop="total"
              header-align="center"
              align="center"
              label="部门总人数"
          >
          </el-table-column>

          <el-table-column v-slot="scope"
                           prop="total"
                           header-align="center"
                           align="center"
                           label="点击查看用户列表"
          >
<!--            <a href="javascript:;" @click="getUserListByDeptId(scope.row)">点击查看列表</a>-->
              <el-button
                  plain
                  v-has-permission="'clientDept:viewList'"
                  type="primary"
                  size="small"
                  icon="el-icon-more"
                  @click="getUserListByDeptId(scope.row)"
              >点击查看列表</el-button
              >
          </el-table-column>
          <el-table-column
              fixed="right"
              header-align="center"
              align="center"
              width="230"
              label="操作"
          >
            <template v-slot="scope">
              <el-tooltip content="添加" placement="top" effect="light">
              <el-button
                  circle round plain
                  v-has-permission="'clientDept:add'"
                  type="primary"
                  size="small"
                  icon="el-icon-circle-plus-outline"
                  @click="openAdd(scope.row)"
              ></el-button
              >
              </el-tooltip>
              <el-tooltip content="修改" placement="top" effect="light">
              <el-button
                  circle round plain
                  v-has-permission="'clientDept:edit'"
                  type="primary"
                  size="small"
                  icon="el-icon-edit"
                  @click="edit(scope.row)"
              ></el-button
              >
              </el-tooltip>

              <el-tooltip content="删除" placement="top" effect="light">
                <el-button
                    circle round plain
                    v-has-permission="'clientDept:delete'"
                    type="danger"
                    size="small"
                    icon="el-icon-delete"
                    @click="delNode(scope.row.deptId)"
                ></el-button
                >
              </el-tooltip>
              <el-tooltip content="一键恢复" placement="top" effect="light">
                <el-button
                    circle round plain
                    v-has-permission="'clientDept:allUpdate'"
                    type="success"
                    size="small"
                    icon="el-icon-refresh"
                    @click="updateAllClient(scope.row.deptId)"
                ></el-button
                >
              </el-tooltip>
              <el-tooltip content="一键清除" placement="top" effect="light">
                <el-button
                    circle round plain
                    v-has-permission="'clientDept:allDelete'"
                    type="danger"
                    size="small"
                    icon="el-icon-delete"
                    @click="delAllClient(scope.row.deptId)"
                ></el-button
                >
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!-- 节点新增弹出框 -->
    <el-dialog :title="addTitle" :visible.sync="addDialogVisible" @close="addClose" width="50%">
      <span>
        <el-form
            size="mini"
            ref="addFormRef"
            :model="addForm"
            label-width="80px"
            :rules="addFormRules"
        >
          <el-form-item label="部门名称" prop="deptName">
            <el-input v-model="addForm.deptName"></el-input>
          </el-form-item>
         <el-form-item label="父分类" prop="pid" v-if="parentCategorys.length>0">
          <el-cascader
              @change="selectParentChange"
              :change-on-select="true"
              :options="parentCategorys"
              clearable
              filterable
              style="width:100%"
              :props="selectProps"
              v-model="pKeys"
          ></el-cascader>
        </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="addForm.remarks"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNode">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑节点弹出框 -->
    <el-dialog :title="editTitle" :visible.sync="editlogVisible" width="50%" @close="editClose">
      <span>
        <el-form
            size="mini"
            ref="editFormRef"
            :model="editForm"
            label-width="80px"
            :rules="addFormRules"
        >
          <el-form-item label="部门名称" prop="deptName">
            <el-input v-model="editForm.deptName"></el-input>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="editForm.remarks"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editlogVisible = false">取 消</el-button>
        <el-button
            type="primary"
            @click="updateDept"
        >确 定</el-button>
      </span>
    </el-dialog>


    <!-- 上传标签弹出层 -->
    <div v-if="isVisible" class="popups" @click.self="isVisible=false">
      <el-main style="width: 42.5vw;height: 50vh">
        <div class="header">
          <h3 style="flex: 1">用户列表</h3>
          <el-tooltip content="关闭页面" placement="top" effect="light">
            <el-button icon="el-icon-circle-close" circle  @click="isVisible=false"></el-button>
          </el-tooltip>
        </div>
        <div style="padding-left: 1vh">
          <div>
            <el-table
                :data="users"
                border
                :header-cell-style="headerCellStyle"
            >
              <el-table-column prop="userName" label="用户名" width="97" />
              <el-table-column prop="nickName" label="用户账号" width="97" />
              <el-table-column prop="phone" label="手机号" width="106" />
              <el-table-column prop="email" label="邮箱" width="150" />
              <el-table-column prop="createTime" label="创建时间" width="150" />
            </el-table>
<!--            <div v-if="!users.length" class="no-data">暂无数据</div>-->
          </div>
        </div>
      </el-main>
    </div>

  </div>
</template>

<script>
import axios from "axios";
import ElectUsersBox from "@/components/electUsersBox.vue";
let id = 1000;

export default {
  components: {ElectUsersBox},
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },

  data() {
    const data = [];

    return {
      isVisible:false,
      btnLoading: false,
      btnDisabled: false,
      loading: true,
      open: [], //展开节点
      filterText: "", //节点过滤文本
      addDialogVisible: false, //新增节点弹出框
      editlogVisible: false, //编辑节点弹出框
      addTitle: "",
      editTitle: "",
      users:[],
      addForm: {
        parentId: "",
        deptName: "",
        remarks: ""
      }, //添加请求表单数据
      editForm: {}, //编辑节点表单数据
      addFormRules: {
        deptName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
          { min: 2, max: 30, message: "长度在 2 到 30 个字符", trigger: "blur" }
        ]
      }, //添加表单验证规则
      pNode: {}, //父节点
      data: JSON.parse(JSON.stringify(data)),

      defaultProps: {
        children: "children",
        label: "deptName"
      },
      selectProps: {
        expandTrigger: "hover",
        value: "deptId",
        label: "deptName",
        children: "children"
      }, //级联选择器配置项
      pKeys: [],
      parentCategorys: []
    };
  },
  created() {
    this.getDeptTree();
    setTimeout(() => {
      this.loading = false;
    }, 500);
  },
  methods: {
    // 自定义表头样式
    headerCellStyle() {
      return { background: "#f5f7fa", color: "#333", fontWeight: "bold" };
    },
    //父级分类中改变
    selectParentChange() {
      const len = this.pKeys.length;
      if (len > 0) {
        this.addForm.parentId = this.pKeys[len - 1];
      } else {
        this.addForm.parentId = 0;
      }
    },

    //更新菜单
    async updateDept() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return;
        } else {
          this.btnLoading = true;
          this.btnDisabled = true;
          const {data: res} = await this.$http.put(
              "system/dept/update/" + this.editForm.deptId,
              this.editForm
          );
          if (res.success) {
            this.$message({
              title: "成功",
              message: "部门信息更新",
              type: "success"
            });
            this.editForm = {};
            this.editlogVisible = false;
            await this.getDeptTree();
          } else {
            this.btnLoading = false;
            this.btnDisabled = false;
            return this.$message.error("更新部门失败" + res.data.errorMsg);
          }
        }
      });
    },
    //点击编辑节点
    async edit(data) {
      this.editTitle = "编辑：【" + data.deptName + "】";
      const {data: res} = await this.$http.get("system/dept/edit/" + data.deptId);
      if (res.success) {
        this.editForm = res.data;
        this.editlogVisible = true;
      } else {
        return this.$message.error("部门编辑失败:" + res.data.errorMsg);
      }
    },
    //过滤节点
    filterNode(value, data) {
      if (!value) return true;
      return data.deptName.indexOf(value) !== -1;
    },
    //关闭添加
    addClose() {
      this.$refs.addFormRef.clearValidate();
      this.addForm = {};
    },
    editClose() {
      this.$refs.editFormRef.clearValidate();
      this.editForm = {};
    },
    //加载菜单树
    async getDeptTree() {
      const {data: res} = await this.$http.get("system/dept/tree");
      if (res.success) {
        console.log("*****************************",res.data.tree)
        this.data = res.data.tree;
        this.open = res.data.open;
      }
    },
    getParentCategoryList() {
      this.$http.get("system/dept/tree").then((res) => {
        if (res.data.success) {
          console.log(res.data.data.tree)
          this.parentCategorys = res.data.data.tree;
        }
      });

    },
    //打开添加框
    openAdd(data) {
      this.addTitle = "添加部门 ：当前【" + data.deptName + "】";
      this.addDialogVisible = true;
      this.addForm.parentId = data.deptId;
      this.pNode = data;
      this.getParentCategoryList();
    },
    //添加最高父级节点
    openParentAdd(data) {
      this.parentCategorys=[];
      this.addTitle = "添加第一父级";
      this.addDialogVisible = true;
      this.addForm.parentId = 0;
    },
    //点击删除按钮
    async delNode(deptId) {
      const res = await this.$confirm(
          "此操作将永久删除该部门,以及清除该部门下的所有数据, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
      if (res === "confirm") {
        await this.delAllClient(deptId);
        console.log(deptId);
        const {data: res} = await this.$http.delete(
            "system/dept/delete/" + deptId
        );
        if (res.success) {
          this.$message.success("部门删除成功");
          await this.getDeptTree();
        } else {
          this.$message.error("部门删除失败:" + res.data.errorMsg);
        }
      }
    },
    async delAllClient(deptId){
      const res = await this.$confirm(
          "此操作将一键清除该部门及下级部门中的所有用户, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消一键清除"
        });
      });
      if (res === "confirm") {
        console.log(deptId);
        const {data: res} = await this.$http.delete(
            "system/dept/allDelete/" + deptId
        );
        if (res.success) {
          this.$message.success("一键清除成功");
          await this.getDeptTree();
        } else {
          this.$message.error("一键清除失败:" + res.data.errorMsg);
        }
      }
    },
    async updateAllClient(deptId){
      const res = await this.$confirm(
          "此操作将一键恢复该部门及下级部门中的所有用户, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消一键恢复"
        });
      });
      if (res === "confirm") {
        console.log(deptId);
        const {data: res} = await this.$http.delete(
            "system/dept/allUpdate/" + deptId
        );
        if (res.success) {
          this.$message.success("一键恢复成功");
          await this.getDeptTree();
        } else {
          this.$message.error("一键恢复失败:" + res.data.errorMsg);
        }
      }
    },
    //发送添加节点请求,保存菜单信息
    async addNode() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return;
        } else {
          this.btnLoading = true;
          this.btnDisabled = true;
          const {data: res} = await this.$http.post("system/dept/add", this.addForm);
          if (res.success) {
            this.$message.success("部门添加成功");
            this.addDialogVisible = false;
            await this.getDeptTree();
          } else {
            this.$message.error("部门添加失败:" + res.data.errorMsg);
          }
          this.btnLoading = false;
          this.btnDisabled = false;
        }
      });
    },
    //前端添加部门节点
    append(data, newChild) {
      //   var newChild = { id: 1231, label: "qqqqq", children: [] };
      if (!data.children) {
        this.$set(data, "children", []);
      }
      data.children.push(newChild);
    },

    remove(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex(d => d.menuId === data.menuId);
      children.splice(index, 1);
    },

    //根据部门查看用户列表
    async getUserListByDeptId(data) {
      this.isVisible=true
      const {data: res} = await this.$http.get("system/dept/getUser/"+data.deptId);
      if (res.success) {
        this.users = res.data;
      }
    },

  }
};
</script>

<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.popups{
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0%;
  left: 0%;
  background-color: #00000042;
  z-index: 100;
}
.popups .el-main{
  background-color: #fff;
  margin: 15vh auto;
}
.popups .el-main .header{
  display: flex;
  justify-content: center;
  margin-bottom: 2vh;
}
.popups .el-main .header button {
  flex-shrink: 0; /* 防止收缩 */
  font-size: 3vh;
  height: 4.6vh;
  border: none;
}
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-row .el-col{
  font-size: 14px;
}
.el-row .el-col label{
  color:#5e6d82;
}
</style>
